package Controller.DepServlet;

import Dao.DepDao;
import bean.Dep;
import com.alibaba.fastjson.JSON;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

@WebServlet("/dep_alter")
public class dep_alter extends HttpServlet {
    DepDao depDao = new DepDao();

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        resp.setContentType("text/html;charset=utf-8");
        String dno = req.getParameter("dno");
        String dname = req.getParameter("dname");
        String tel = req.getParameter("tel");
        boolean flag = false;

        ArrayList<Dep> depList = depDao.selectAll();
        for (Dep dep : depList) {
            if (!dep.getDno().equals(dno) && dep.getDname().equals(dname)) {//检查部门名称是否重复
                flag = true;
                break;
            }
        }
        Map<String, Object> map = new HashMap<>();
        map.put("code", 200);
        if (flag) {
            map.put("msg", "部门名称重复");
            map.put("code", 400);
        } else {
            depDao.update(dno, dname, tel);
            map.put("msg", "修改成功");
        }
        resp.getWriter().write(JSON.toJSONString(map));
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }
}
